package com.leemz.basicui.slice;

import com.leemz.basicui.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.window.dialog.ToastDialog;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        setClickedListener(this,
                findComponentById(ResourceTable.Id_ui_text),
                findComponentById(ResourceTable.Id_ui_button),
                findComponentById(ResourceTable.Id_ui_textfield),
                findComponentById(ResourceTable.Id_ui_image));
    }

    private void setClickedListener(Component.ClickedListener listener, Component... components) {
        for (Component component : components) {
            if(null == component) {
                continue;
            }
            component.setClickedListener(listener);
        }
    }

    @Override
    public void onClick(Component component) {
        String className = "";
        switch (component.getId()) {
            case ResourceTable.Id_ui_text:
                className = "com.leemz.basicui.slice.TextSlice";
                break;
            case ResourceTable.Id_ui_button:
                className = "com.leemz.basicui.slice.ButtonSlice";
                break;
            case ResourceTable.Id_ui_textfield:
                className = "";
                break;
            case ResourceTable.Id_ui_image:
                className = "";
                break;
            default:
                break;
        }
        jumpSlice(className);
    }

    private void jumpSlice(String className) {
        if("".equals(className)) {
            return;
        }
        try{
            Class cls = Class.forName(className);
            Object slice = cls.newInstance();
            if(slice instanceof AbilitySlice) {
                present((AbilitySlice) slice, new Intent());
            }
        } catch (Exception ex) {
            new ToastDialog(getContext())
                    .setText("Error!")
                    .show();
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
